#include <gpiod.h>
#include <stdio.h>
#include <stdlib.h>

// 通过按键控制音量
// key2 音量+
// key3 音量-
int main(int argc, char **argv)
{
    struct gpiod_line_bulk keys;
    struct gpiod_chip *gpiof = gpiod_chip_open_by_label("GPIOF");
    if (!gpiof)
    {
        perror("gpiod_chip_open");
        return EXIT_FAILURE;
    }

    unsigned int lines[] = {7, 8};

    if (gpiod_chip_get_lines(gpiof, lines, 2, &keys) < 0)
    {
        perror("gpiod_chip_get_lines");
        gpiod_chip_close(gpiof);
        return EXIT_FAILURE;
    }

    if (gpiod_line_request_bulk_falling_edge_events(&keys, "keys") < 0)
    {
        perror("gpiod_line_request_bulk_falling_edges_events");
        gpiod_chip_close(gpiof);
        return EXIT_FAILURE;
    }

    while (1)
    {
        // 等待按键状态改变
        struct gpiod_line_bulk pressed;

        if (gpiod_line_event_wait_bulk(&keys, NULL, &pressed) < 0)
        {
            perror("gpiod_line_event_wait_bulk");
        }

        // 检测按下的按键
        struct gpiod_line *key;
        int offset;
        gpiod_line_bulk_foreach_line_off(&pressed, key, offset)
        {
            // 读取按键事件
            struct gpiod_line_event event;
            gpiod_line_event_read(key, &event);
            // 根据引脚编号判断按键位置
            if (gpiod_line_offset(key) == 7)
            {
                printf("key2 pressed\n");
                system("amixer set Analog 10%+");
            }

            if (gpiod_line_offset(key) == 8)
            {
                printf("key3 pressed\n");
                system("amixer set Analog 10%-");
            }
        }
    }

    gpiod_line_release_bulk(&keys);
    gpiod_chip_close(gpiof);

    return 0;
}